/* eslint-disable vue/no-parsing-error */
<!--
 * @Author: Christion.Young
 * @Date: 2020-10-16 17:47:18
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-03-16 13:33:32
 * @Description: file content
-->
<template>
    <div>
        <div class="titleBox">执行操作</div>
        <el-form ref="BusinessForm"
                 :model="BusinessForm"
                 label-width="100px">
            <el-form-item label="执行动作：">
                <el-radio-group v-model="BusinessForm.performAction">
                    <el-radio :label="1">导出</el-radio>
                    <el-radio :label="2">导入(全量)</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="BusinessForm.performAction==1?true:false"
                          label="导出内容：">
                <el-checkbox-group v-model="BusinessForm.export">
                    <el-checkbox label="pub"
                                 disabled>公共数据</el-checkbox>
                    <el-checkbox label="rul">规则数据</el-checkbox>
                    <el-checkbox label="log">操作日志</el-checkbox>
                    <el-checkbox label="tmp">用户查询模板</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="BusinessForm.performAction!==1?true:false"
                          label="导入内容：">
                <div class="channelBox">
                    <el-upload ref="upload"
                               :multiple="false"
                               action
                               :limit="1"
                               :file-list="fileList"
                               :on-exceed="handleExceed"
                               :before-upload="beforeAvatarUpload"
                               :before-remove="beforeRemove"
                               :http-request="httpRequest">
                        <div class="channelI"><i class="el-icon-upload" /></div>
                        <div slot="tip">只能上传mds文件</div>
                    </el-upload>
                </div>
            </el-form-item>
        </el-form>
        <div class="btnBox">
            <el-button @click="onExecute">执行</el-button>
            <el-button @click="onReset">重置</el-button>
            <!-- <el-button @click="test">测试</el-button> -->
        </div>
        <!-- <div class="titleBox">日志浏览</div> -->
        <!-- <div class="contentBox">
            <div v-for="(item,index) in dataLog"
                 :key="item+index"
                 class="contentLog">{{item}}</div>
        </div> -->
    </div>
</template>

<script>
import moment from 'moment'
import { caPubDriver } from '@/api/index'
export default {
    name: '',
    data: function () {
        return {
            BusinessForm: {
                performAction: 1,
                export: ['pub'],
            },
            dataLog: [],
            fileList: [],
            fileData: {},
            timer: '',
        }
    },
    computed: {},
    watch: {},
    created() {},
    beforeDestroy() {
        clearInterval(this.timer)
    },
    methods: {
        beforeRemove(file) {
            let str = ''
            if (file.name) {
                str = file.name.substring(file.name.length - 4)
            } else {
                str = ''
            }
            const isMDS = str === '.mds'
            if (!isMDS) {
                return 
            } else {
                return this.$confirm(`确定移除${file.name}?`)
            }
        },
        beforeAvatarUpload(file) {
            let str = ''
            if (file.name) {
                str = file.name.substring(file.name.length - 4)
            } else {
                str = ''
            }
            const isMDS = str === '.mds'
            if (!isMDS) {
                this.$message.error('上传文件只能是mds格式！')
            }
            return isMDS
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择1个文件，本次选择了${
                    files.length
                }个文件，共选择了${files.length + fileList.length}个文件`
            )
        },
        //执行
        onExecute() {
            this.getPrograssMsg()
            switch (this.BusinessForm.performAction) {
                case 1:
                    this.exportFile()
                    break
                case 2:
                    if (JSON.stringify(this.fileData) === '{}') {
                        this.$message.warning('请先选择文件！')
                    } else {
                        this.uploadFile(this.fileData)
                    }
                    break
                default:
                    break
            }
        },
        //重置
        onReset() {
            clearInterval(this.timer)
            this.dataLog = []
            switch (this.BusinessForm.performAction) {
                case 1:
                    this.BusinessForm.export = ['pub']
                    break
                case 2:
                    this.$refs.upload.clearFiles()
                    break
                default:
                    break
            }
        },
        getPrograssMsg() {
            // this.timer = setInterval(() => {
            //     caPubDriver.getPrograssMsg().then(res => {
            //         this.dataLog.push(res.data)
            //         if (res.data == null || res.data == '' || res.data == 'null说明接口已经调通了！！！') {
            //             clearInterval(this.timer)
            //         }
            //     })
            // }, 500)
        },
        // test() {
        //      caPubDriver.getPrograssMsg().then(res => {
        //             this.dataLog.push(res.data)
        //             if (res.data == null || res.data == '' || res.data == 'null说明接口已经调通了！！！') {
        //                 //clearInterval(this.timer)
        //             }
        //         })
        // },
        httpRequest(item) {
            this.fileData = item
            console.log(item, '=============')
        },
        //导入
        uploadFile(item) {
            const form = new FormData()
            // const blob = new Blob()
            const file = item.file
            console.log(file)
            form.append('upload', file)
            caPubDriver.importFile(form).then((response) => {
                if (response.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '上传成功！',
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '上传失败！',
                    })
                }
            })
        },
        //导出
        exportFile() {
            let data = {
                log: '',
                pub: '',
                rul: '',
                tmp: '',
            }
            for (let i = 0; i < this.BusinessForm.export.length; i++) {
                switch (this.BusinessForm.export[i]) {
                    case 'pub':
                        this.$set(data, 'pub', '1')
                        break
                    case 'log':
                        this.$set(data, 'log', '1')
                        break
                    case 'rul':
                        this.$set(data, 'rul', '1')
                        break
                    case 'tmp':
                        this.$set(data, 'tmp', '1')
                        break
                    default:
                        break
                }
            }
            caPubDriver.exportFile(data).then((response) => {
                if (response.data) {
                    console.log(response, 'response205')
                    var filename = decodeURI(response.headers['content-disposition']).split('=')[1];
                    var blob = new Blob([response.data], {
                        type: 'application/octet-stream',
                    })
                    if (window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveBlob(blob,filename)
                    } else {
                        var downloadElement = document.createElement('a')
                        var href = window.URL.createObjectURL(blob) //创建下载的链接
                        downloadElement.href = href
                        downloadElement.download = filename //下载后文件名
                        document.body.appendChild(downloadElement)
                        downloadElement.click() //点击下载
                        document.body.removeChild(downloadElement) //下载完成移除元素
                        window.URL.revokeObjectURL(href) //释放掉blob对象
                    }
                } else {
                    this.$message.error(response.data.message || '获取失败')
                }
            })
        },
    },
}
</script>

<style lang="scss" scoped>
.titleBox {
    width: calc(100% - 20px);
    height: 40px;
    border-bottom: 2px solid #ededed;
    padding: 10px;
    line-height: 20px;
    margin: 10px;
    font-weight: 900;
}
.contentBox {
    width: calc(100% - 20px);
    height: 300px;
    margin: 20px;
    border: 1px solid;
    padding: 10px;
    overflow-y: auto;
}
.contentLog {
    width: 100%;
    height: 20px;
    line-height: 20px;
    margin-bottom: 10px;
}
.channelBox {
    display: flex;
    width: 220px;
    .channelI {
        width: 32px;
        height: 32px;
        font-size: 22px;
        border: 1px solid;
        border-radius: 16px;
        text-align: center;
        line-height: 30px;
        margin-left: 10px;
        color: blue;
    }
}
.btnBox {
    width: 180px;
    margin-left: 28px;
}
</style>
